<?php
declare (strict_types = 1);

namespace daayu\taskload\service;

use daayu\taskload\TaskLoadConfig;

/**
 * 计划任务服务器Service层
 */
class TaskProjectService extends BaseService
{
    protected $table = 'zn_task_project';

    public function listName(){
        return $this->table()->column('name', 'id');
    }

    public function list($args = [])
    {
        $page = isset($args['page']) ? intval($args['page']) : 1;
        $rows = isset($args['rows']) ? intval($args['rows']) : 20;
        $field = isset($args['field']) ? trim($args['field']) : 'id,name,key,describe,status,create_time,update_time';
        $orderBy = isset($args['order_by']) ? $args['order_by'] : 'id desc';
        $where = [];
        if(isset($args['id'])){
            if(is_array($args['id'])){
                $where[] = ['id', 'in', $args['id']];
            }elseif(intval($args['id']) > 0){
                $where[] = ['id', '=', intval($args['id'])];
            }
        }
        if(isset($args['name']) && !empty($args['name'])){
            $where[] = ['name', 'like', '%' . trim($args['name']) . '%'];
        }
        if(isset($args['status']) && $args['status'] > -1){
            $where[] = ['status', '=', intval($args['status'])];
        }
        $rs = $this->table()->where($where)->page($page, $rows)->field($field)->order($orderBy)->select()->toArray();
        if(!empty($rs)){
            foreach($rs as $k => &$v){
                if(isset($v['status'])){
                    $v['status_text'] = $this->status_names[$v['status']] ?? '';
                }
            }
        }
        $ret['total'] = isset($args['total']) ? $args['total'] : $this->table()->where($where)->count();
        $ret['page'] = $page;
        $ret['rows'] = $rs;
        return $ret;
    }

    public function get($id, $field=null)
    {
        $id = intval($id);
        if($id <= 0){
            $this->error = '参数错误';
            return false;
        }
        $info = $this->table()->where('id', $id)->field($field)->find();
        if(!$info){
            $this->error = '指定的记录不存在';
            return false;
        }
        return $info;
    }

    public function save($data = [])
    {
        $id = 0;
        if(isset($data['id'])){
            $id = intval($data['id']);
            unset($data['id']);
            if(empty($id) || $this->table()->where('id', $id)->value('id') == null){
                $this->error = '指定的记录不存在';
                return false;
            }
        }
        //验证数据
        if(isset($data['name'])){
            $data['name'] = trim($data['name']);
            if(empty($data['name'])){
                $this->error = '名称不能为空';
                return false;
            }
            $exist_id = $this->table()->where('name', '=', $data['name'])->where('id','not in', [$id])->value('id');
            if($exist_id){
                $this->error = '名称不能重复';
                return false;
            }
            $data['key'] = md5($data['name']);
        }
        if(isset($data['describe'])){
            $data['describe'] = trim($data['describe']);
        }
        if(isset($data['status'])){
            $data['status'] = intval($data['status']);
            if(!in_array($data['status'], [0,1])){
                $this->error = '状态不正确，只能为[0,1]';
                return false;
            }
        }
        if($id > 0){
            $r = $this->table()->where('id', $id)->update($data);
        }else{
            $id = $this->table()->insertGetId($data);
        }
        return $id;
    }

    public function delete($id){
        $id = intval($id);
        if($id <= 0){
            $this->error = '参数错误';
            return false;
        }
        // 启动事务
        $this->db()->startTrans();
        try {
            $r = $this->table()->where('id', $id)->delete();
            //删除相关
            $r = $this->table(TaskLoadConfig::TABLE_TASK_PLAN)->where('project_id', $id)->delete();
            $r = $this->table(TaskLoadConfig::TABLE_TASK_SERVER_PROJECT)->where('project_id', $id)->delete();
            $r = $this->table(TaskLoadConfig::TABLE_TASK_SERVER_RELATE)->where('project_id', $id)->delete();
            // 提交事务
            $this->db()->commit();
            return $r;
        } catch (\Exception $e) {
            // 回滚事务
            $this->db()->rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }

    public function createDb()
    {
        if(!$this->checkTable()){
            $sql = "CREATE TABLE `".$this->table."`  (
                `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
                `name` varchar(100) DEFAULT '' COMMENT '项目名字',
                `key` varchar(32) DEFAULT '' COMMENT '项目唯一标识key',
                `status` tinyint(4) DEFAULT '0' COMMENT '状态 0禁用 1正常',
                `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
                `describe` varchar(1000) DEFAULT '' COMMENT '描述',
                PRIMARY KEY (`id`)
                ) ENGINE=InnoDB COMMENT='任务工程表' ROW_FORMAT = Dynamic";
            $this->db()->execute($sql);
        }
    }
}
